package com.leimingkun.mq.conf;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * desc:TTL队列 配置文件类代码
 */
@Configuration
public class TtlQueueConfig {
    // ====================== 业务队列（含TTL和死信配置） ======================
    public static final String BUSINESS_QUEUE = "leiQueue";         // 业务队列名称
    public static final String BUSINESS_EXCHANGE = "leiDirect";     // 业务交换机名称
    public static final String BUSINESS_ROUTING_KEY = "leiRoutingKey"; // 业务路由键

    // ====================== 死信队列（DLQ）配置 ======================
    public static final String DLQ_QUEUE = "dlq.leiQueue";          // 死信队列名称
    public static final String DLQ_EXCHANGE = "dlq.leiDirect";      // 死信交换机名称
    public static final String DLQ_ROUTING_KEY = "dlq.leiRoutingKey"; // 死信路由键

    // ====================== 业务交换机 ======================
    @Bean
    public DirectExchange businessExchange() {
        return new DirectExchange(BUSINESS_EXCHANGE);
    }

    // ====================== 死信交换机 ======================
    @Bean
    public DirectExchange dlqExchange() {
        return new DirectExchange(DLQ_EXCHANGE);
    }

    // ====================== 业务队列（设置TTL和死信参数） ======================
    @Bean
    public Queue businessQueue() {
        Map<String, Object> args = new HashMap<>();
        // 队列级TTL：消息在队列中最长存活时间（单位：毫秒）
        args.put("x-message-ttl", 5000); // 30秒过期
        // 绑定死信交换机和路由键
        args.put("x-dead-letter-exchange", DLQ_EXCHANGE);
        args.put("x-dead-letter-routing-key", DLQ_ROUTING_KEY);

        // durable=true：队列持久化（重启后不丢失）
        return new Queue(BUSINESS_QUEUE, true, false, false, args);
    }

    // ====================== 死信队列 ======================
    @Bean
    public Queue dlqQueue() {
        // 死信队列无需TTL，直接监听即可
        return new Queue(DLQ_QUEUE, true); // 持久化队列
    }

    // ====================== 业务队列与业务交换机绑定 ======================
    @Bean
    public Binding businessBinding() {
        System.out.println("绑定业务队列到交换机");
        return BindingBuilder.bind(businessQueue())
                .to(businessExchange())
                .with(BUSINESS_ROUTING_KEY);
    }

    // ====================== 死信队列与死信交换机绑定 ======================
    @Bean
    public Binding dlqBinding() {
        System.out.println("绑定死信队列到交换机");
        return BindingBuilder.bind(dlqQueue())
                .to(dlqExchange())
                .with(DLQ_ROUTING_KEY);
    }
 
}